﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Main : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();

            }
        }

        public void FillData()
        {
            var sql = string.Format("select id ID,title 标题,Content 内容,Author 作者,Remarks 备注 from Articles");
            
            GridView1.DataSource=DbHelper.data(sql);
            GridView1.DataBind();


        }
        
        //取消ing编辑事件
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            FillData();

        }

        //编辑ing事件
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillData();
        }

        //删除ing事件
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var Id = GetValue(e.RowIndex,1);
            var sql = string.Format("delete from Articles where Id='{0}'", Id);
            DbHelper.AddOrUpdateOrDelete(sql);

           
            FillData();

        }

        //更新ing事件
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var Id = GetValue(e.RowIndex, 1);
            var title = GetValue(e.RowIndex, 2);
            var Content = GetValue(e.RowIndex, 3);
            var Author = GetValue(e.RowIndex, 4);
            var Remarks = GetValue(e.RowIndex, 5);

            var sql = string.Format("update Articles set Title='{0}',Content='{1}',Author='{2}',Remarks='{3}' where id='{4}'",title,Content,Author,Remarks,Id);
            DbHelper.AddOrUpdateOrDelete(sql);

            GridView1.EditIndex = -1;
            FillData();
        }

        public string GetValue(int rowIndex,int cellIndex)
        {
            var conctol = GridView1.Rows[rowIndex].Cells[cellIndex];

            var res = conctol.Controls.Count > 0 ? ((TextBox)conctol.Controls[0]).Text : conctol.Text;

            return res;

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddContent.aspx");
        }
    }
}